define(['moment'], function (moment) {
    return ['$state', '$scope', '$rootScope', '$filter', '$stateParams', 'config', 'MMWService', '$mdDialog', '$timeout','$calculater','$mddProvider',
        function ($state, $scope, $rootScope, $filter, $stateParams, config, $MMWService, $mdDialog, $timeout, $calculater, $mddProvider) {
            $scope._event = {};
            $scope._fn = {};
            $scope.mode = 'init';
            var select_count = 0,
                favourite_outsource = JSON.parse(localStorage.getItem(config.appName + '_favourite_outsource'));
            $scope.checkBoxList = {};
            $scope.outsourceInfo = {
                outsourcers_no: moment(new Date()).format('YYYYMMDDHHmmss'),
                op_no: '', outsourcers_company_no: '',
                outsourcing_info_detail: [], plot_no: '', qty: '', erp_doc_type: '',
                disp_start_time: moment(new Date()).format('YYYY/MM/DD'),
                disp_end_time: moment((new Date()).setDate((new Date()).getDate() + 1)).format('YYYY/MM/DD')
            };
            $scope.filterItem = {};
            $scope.init = function () {
                $scope.tempCheck = [];
                $scope.checkAll = false;
                $scope.warehouseInfo = {};
                if(favourite_outsource !== null){
                    $scope.outsourceInfo.outsourcers_company_no = favourite_outsource.outsourcers_company_no;
                    $scope.outsourceInfo.erp_doc_type_display = favourite_outsource.erp_doc_type_display;
                    $scope.outsourceInfo.erp_doc_type = favourite_outsource.erp_doc_type;
                    $scope.outsourceInfo.op_no = favourite_outsource.op_no;
                    if($scope.outsourceInfo.op_no && $scope.outsourceInfo.op_no != ''){
                        outSourceInfoGet(function (response) {
                            $scope.outsourceInfo.outsourcing_info_detail = response;
                            select_count = 0;
                            $scope.checkAll = false;
                        });
                    }
                }
                $scope.PageConfig = {
                    page : 0,
                    page_count : 25
                };
                $scope.mode = 'init';
                $scope.printList = []; // 列印詳情
                $scope.FasteningPackage = config.cache.sys_parameter.FasteningPackage; // 紧固件行业包 → 0(關閉) ; 1(開啟)
                // 20230314 modify by Alan for#130010: 紧固件行业包卡控顯示雙單位
                if($scope.FasteningPackage == 1 || $scope.FasteningPackage == 'Y'){
                    $scope._event['outsourcing_info_detail.molecule'].isShown = 'Y';
                    $scope._event['outsourcing_info_detail.vehicle_no'].isShown = 'Y';

                    vehicle_no_info_get('', function(itemList){
                        $scope.vehicleList = itemList; // 載具list
                    });
                } else {
                    $scope._event['outsourcing_info_detail.molecule'].isShown = 'N';
                    $scope._event['outsourcing_info_detail.vehicle_no'].isShown = 'N';
                }
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            $scope.$watch('outsourceInfo.outsourcing_info_detail', (b) => {
                if (b.length > 0) {
                    $scope._event['plot_no'].isDisabled = 'N';
                    $scope._fn['btn_search'].isDisabled = 'N';
                    $scope._fn['btn_calculate'].isDisabled = 'N';

                } else {
                    $scope._event['plot_no'].isDisabled = 'Y';
                    $scope._fn['btn_search'].isDisabled = 'Y';
                    $scope._fn['btn_calculate'].isDisabled = 'Y';
                }
            });

            $scope.getPages = function(list, PageConfig, filterItem, orderItem){
                if (list) {
                    var temp_list = list.filter(function(item, index, array){
                        var isOK = true,
                            keys = Object.keys(filterItem);
                        for(var i =0; i<keys.length;i++){
                            var key = keys[i];
                            if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                                if(item[key].indexOf(filterItem[key]) == -1){
                                    isOK = false;
                                    break;
                                }
                            }
                        }
                        return isOK;
                    });
                    if(PageConfig){
                        PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count)||1;
                        if(PageConfig.page >= PageConfig.total_page){
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page*PageConfig.page_count;
                        return temp_list.slice(index, index+PageConfig.page_count);
                    } else {
                        return temp_list;
                    }
                } else {
                    return list;
                }
            };

            $scope._event['op_no'] = {
                click: () => {
                    $scope.loadOpNo();
                }
            };
            $scope.loadOpNo = function (callback){
                $MMWService.showQueryListPNIG({
                    form_name: 'PageNo_37',
                    header: [
                        {label:$filter('translate')('B0216.queryList.column2_1'), code:'page_no'},
                        {label:$filter('translate')('B0216.queryList.column2_2'), code:'page_name'}
                    ],
                    setCondition:function(conditions){
                        conditions.push({column_name:'OSOption', query_mode:'1', value:'0', merge_condition_model:'AND' });
                        return conditions;
                    },
                    confirm : function(selectItem){
                        if(callback){
                            callback(selectItem);
                        } else {
                            $scope.outsourceInfo.op_no = selectItem.page_no;
                            outSourceInfoGet(function (response) {
                                $scope.outsourceInfo.outsourcing_info_detail = response;
                                select_count = 0;
                                $scope.checkAll = false;
                            });
                        }
                    }
                });
            };

            //20170331 modify by megabytes for 內存外顯
            $scope._event['outsourcers_company_no'] = {
                click: () => {
                    $MMWService.showQueryListPNIG({
                        form_name: 'PageNo_4',
                        condition: [
                            { name: $filter('translate')('B0216.queryList.column1_1'), column_name: 'SubcontractorNo', query_mode: '2', value: '' }
                        ],
                        header: [
                            { label: $filter('translate')('B0216.queryList.column1_1'), code: 'page_no' },
                            // 20210330 modify by 奕達 for M#90323
                            { label: $filter('translate')('B0216.queryList.column1_2'), code: 'page_name' }
                        ],
                        confirm: function (selectItem) {
                            $scope.outsourceInfo.outsourcers_company_no = selectItem.page_no;
                        }
                    });
                }
            };
            

            $scope._event['erp_doc_type_display'] = {
                click: () => {
                    $scope.loadERP();
                }
            };

            $scope._event['plot_no'] = {
                isDisabled: $scope.outsourceInfo.outsourcing_info_detail.length == 0 ? 'Y' : 'N',
                change: (plot_no, $event) => {
                    if ($event.event.keyCode == 13) {
                        $scope.$root.focusById('plot_no');
                        $scope._fn['btn_search'].click();
                    }
                }

            }

            $scope.loadERP = function (callback) {
                $rootScope.showQueryList({
                    pageRecord:50,
                    header : [
                        {label:$filter('translate')('B0216.queryList.column3_1'), code:'page_no'},
                        {label:$filter('translate')('B0216.queryList.column3_2'), code:'page_name'}
                    ],
                    query: function(conditions, feedback){
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_SYS.erp_document_type_get',
                            content: { doc_type:'4' },
                            success: function (data) {
                                feedback(data);
                            }
                        });
                    },
                    selectCode:$scope.outsourceInfo.erp_doc_type,
                    confirm : function(selectItem, dialog){
                        dialog.hide();
                        if(callback){
                            callback(selectItem);
                        } else {
                            $scope.outsourceInfo.erp_doc_type_display = selectItem.page_no + ' ('+selectItem.page_name+')';
                            $scope.outsourceInfo.erp_doc_type = selectItem.page_no;
                        }
                    }
                });
            };


            // 20220203 modify by Alan for M#127140:    修正單選多選邏輯，限定Q狀態能勾選
            $scope._event['outsourcing_info_detail'] = {
                enableSelect: (item, args) => item.status === 'Q',
                selectAll: (list) => {
                    $scope.checkAll = !$scope.checkAll;
                    $scope._event['outsourcing_info_detail'].isSelectAll = !$scope._event['outsourcing_info_detail'].isSelectAll;
                    //20211025 modify by Liuyang for M#102022:外包出货作业全选按钮只全选当前页
                    let temp_list = $scope._event['outsourcing_info_detail'].getPages($scope.outsourceInfo['outsourcing_info_detail'], $scope.PageConfig, $scope.filterItem);
                    temp_list.forEach(function (item) {
                        if (item.status == 'Q') {
                            if ($scope.checkAll) {
                                $scope.checkBoxList[item.plot_no] = select_count;
                                item.isSelect = true;
                                select_count++;
                            } else {
                                $scope.checkBoxList[item.plot_no] = 99999;
                                item.isSelect = false;
                                select_count--;
                            }

                        }
                    });
                    if (!$scope.checkAll) {
                        select_count = 0;
                        $scope.outsourceInfo.outsourcing_info_detail.forEach(function (item) {
                            $scope.checkBoxList[item.plot_no] = 99999;//設定為99999
                        });
                    }
                },
                click: (item, args) => {
                    item.isSelect = !item.isSelect;
                    if($scope.checkBoxList[item.plot_no] == 99999){
                        $scope.checkBoxList[item.plot_no] = select_count;
                        select_count++;
                    } else {
                        $scope.checkBoxList[item.plot_no] = 99999;
                        select_count--;
                    }
                },
                getPages: (list, PageConfig, filterColumn,header) => {
                    if (list) {  
                        if (header && header.code != "")
                        list = $filter('orderBy')(list, header.code, header.order);                         
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterColumn);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterColumn[key] && filterColumn[key] != '') {
                                    if (item[key].indexOf(filterColumn[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        if (PageConfig) {
                            PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count) || 1;
                            if (PageConfig.page >= PageConfig.total_page) {
                                PageConfig.page = 0;
                            }
                            var index = PageConfig.page * PageConfig.page_count;
                            var result = temp_list.slice(index, index + PageConfig.page_count);
                            return result;
                        } else {
                            return temp_list;
                        }
                    } else {
                        return list;
                    }
                }
            }

            $scope._event['product_warehouse'] = {
                click: () => {
                    $MMWService.pageNumberInfoGet({
                        form_name: 'PageNo_6',
                        query_condition_info: [
                            { column_name: 'InventoryType', query_mode: '0', value: 3 }
                        ]
                    }, function (response) {
                        $scope.$root.showSelect({
                            label: function (item) {
                                return item.page_no + ' (' + item.page_name + ')';
                            },
                            code: 'page_no',
                            selectCode: $scope.warehouseInfo.product_warehouse,
                            list: response,
                            confirm: function (item, dialog) {
                                dialog.hide();
                                $scope.warehouseInfo.product_warehouse_name = item.page_display;
                                $scope.warehouseInfo.product_warehouse = item.page_no;

                                $scope.warehouseInfo.storage = '';
                                $scope.warehouseInfo.storage_display = '';
                            }
                        });
                    });
                }
            }

            //儲位
            $scope._event['storage'] = {
                click: () => {
                    if ($scope.warehouseInfo.product_warehouse && $scope.warehouseInfo.product_warehouse != '') {
                        $MMWService.pageNumberInfoGet({
                            form_name: 'PageNo_7', query_condition_info: [
                                { column_name: 'InventoryNo', query_mode: '0', value: $scope.warehouseInfo.product_warehouse }
                            ]
                        }, function (response) {
                            $scope.$root.showSelect({
                                label: function (item) {
                                    return item.page_no + ' (' + item.page_name + ')';
                                },
                                code: 'page_no',
                                selectCode: $scope.warehouseInfo.storage,
                                list: response,
                                confirm: function (item, dialog) {
                                    dialog.hide();
                                    $scope.warehouseInfo.storage = item.page_no;
                                    $scope.warehouseInfo.storage_display = item.page_display;
                                }
                            });
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('B0216.showAlert.product_warehouse_empty'));
                    }
                }
            }

            $scope._event['erp_doc_type'] = {
                click: () => {
                    $rootScope.showQueryList({
                        pageRecord: 50,
                        header: [
                            { label: $filter('translate')('B0216.queryList.column3_1'), code: 'page_no' },
                            { label: $filter('translate')('B0216.queryList.column3_2'), code: 'page_name' }
                        ],
                        query: function (conditions, feedback) {
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_SYS.erp_document_type_get',
                                content: { doc_type: '2' },
                                success: function (data) {
                                    feedback(data);
                                }
                            });
                        },
                        selectCode: $scope.outsourceInfo.erp_doc_type,
                        confirm: function (selectItem, dialog) {
                            $scope.warehouseInfo.erp_doc_type = selectItem.page_no;
                            dialog.hide();
                        }
                    });
                }
            }
            $scope._event['pdf_panel'] = {
                isShown:'N'
            }
            $scope._event['pdf_footer'] = {
                isShown:'N'
            }

            $scope._event['outsourcing_info_detail.molecule'] = {
                isShown: 'N'
            }

            $scope._event['outsourcing_info_detail.vehicle_no'] = {
                isShown: 'N'
            }

            $scope.$watch('mode', (mode) => {
                if(mode == 'init') {
                    $scope._event['pdf_panel'].isShown = 'N'
                    $scope._event['pdf_footer'].isShown = 'N'
                }
                else if (mode == 'print'){
                    $scope._event['pdf_panel'].isShown = 'Y'
                    $scope._event['pdf_footer'].isShown = 'Y'
                } 
            });

            $scope._fn = {
                'favorite': {//我的最爱
                    click: () => {
                        $mdDialog.dialog(
                            'module/moduleB/program/B02/B0216/B0216_F.html',
                            function (dialog) {
                                return {
                                    favourite_outsource: favourite_outsource || {},
                                    loadOpNo: function () {
                                        $scope.loadOpNo(function (selectItem) {
                                            dialog.favourite_outsource.op_no = selectItem.page_no;
                                        });
                                    },
                                    loadERP: function () {
                                        $scope.loadERP(function (selectItem) {
                                            dialog.favourite_outsource.erp_doc_type_display = selectItem.page_no + ' (' + selectItem.page_name + ')';
                                            dialog.favourite_outsource.erp_doc_type = selectItem.page_no;
                                        });
                                    },
                                    confirm: function () {
                                        favourite_outsource = dialog.favourite_outsource;
                                        localStorage.setItem(config.appName + '_favourite_outsource', JSON.stringify(favourite_outsource));
                                        dialog.hide();
                                        //$scope.outsourceInfo.outsourcers_company_no = favourite_outsource.outsourcers_company_no;
                                        $scope.outsourceInfo.erp_doc_type_display = favourite_outsource.erp_doc_type_display;
                                        $scope.outsourceInfo.erp_doc_type = favourite_outsource.erp_doc_type;
                                        $scope.outsourceInfo.op_no = favourite_outsource.op_no;
                                        outSourceInfoGet(function (response) {
                                            $scope.outsourceInfo.outsourcing_info_detail = response;
                                            select_count = 0;
                                            $scope.checkAll = false;
                                        });
                                    },
                                    back: function () {
                                        dialog.hide();
                                    }
                                };
                            }
                        );
                    }
                },
                'btn_confirm': {
                    isShown: () =>{
                        return ($scope.mode == 'init') ? 'Y' : 'N'
                    },
                    click: () => {
                        if ($scope.outsourceInfo.outsourcers_company_no == undefined || $scope.outsourceInfo.outsourcers_company_no == '') {
                            $rootScope.showAlert($filter('translate')('B0216.showAlert.column1'));
                        } else {
                            var hasModified = false;

                            for (var i = 0; i < $scope.outsourceInfo.outsourcing_info_detail.length; i++) {
                                if ($scope.outsourceInfo.outsourcing_info_detail[i].isSelect) {
                                    hasModified = true;
                                    break;
                                }
                            }

                            if (hasModified) {
                                outsourcingInfoProcess();
                            }
                            else {
                                $rootScope.showAlert($filter('translate')('B0216.showAlert.column2'));
                            }
                        }
                    }
                },
                'btn_search': {//輸入批號後 自動打勾所有相同的批號
                    isDisabled: ($scope.outsourceInfo == undefined || $scope.outsourceInfo.outsourcing_info_detail.length == 0) ? 'Y' : 'N',
                    click: () => {
                        $scope.checkAll = false;
                        // 20200316 modify by WeiTing for M#68196 - 外包出貨，修正輸入批號查詢，不會自動帶到第一筆。
                        $scope.filterItem.plot_no = $scope.outsourceInfo.plot_no;
                        $scope._objoutsourcing_info_detail.filterColumns = $scope.filterItem;
                        $scope.outsourceInfo.outsourcing_info_detail.forEach(function (item) {
                            //調整方法為 like
                            if (item.status == 'Q') {
                                if (item.plot_no.indexOf($scope.outsourceInfo.plot_no) != -1) {
                                    if ($scope.checkBoxList[item.plot_no] == 99999) {
                                        $scope.checkBoxList[item.plot_no] = select_count;
                                        select_count++;
                                        item.isSelect = true;
                                    } else {
                                        $scope.checkBoxList[item.plot_no] = 99999;
                                        select_count--;
                                        item.isSelect = false;
                                    }
                                }
                            }
                        });
                    }
                },
                'btn_calculate': { //20200827 add by Dustdusk for M#77173: 預完日計算
                    isDisabled: ($scope.outsourceInfo == undefined || $scope.outsourceInfo.outsourcing_info_detail.length == 0) ? 'Y' : 'N',
                    click: () => {
                        var _sum = 0;
                        $scope.outsourceInfo.outsourcing_info_detail.forEach(function (item) {
                            if ($scope.checkBoxList[item.plot_no] != 99999 && item.status == 'Q') {
                                //_sum += (1 + item.output_qty * 60);
                                _sum += (item.fix_eqptime + item.output_qty * item.var_eqptime);
                            }
                        });
                        if (!isNaN(_sum))
                            _sum = Math.max(1, Math.ceil(_sum / 60 / 24));
                        else
                            _sum = 1;
                        $scope.outsourceInfo.disp_end_time = moment($scope.outsourceInfo.disp_start_time).add('days', _sum)._i;//toDate();
                    }
                },
                //toolBar
                'outsourcing_info_detail.B0208': {//暂停
                    isShown: (item, args) => {
                        return ['Q'].includes(item.status) ? 'Y' : 'N';
                    },
                    click: (item, args) => {
                        $mdDialog.serviceDialog(args.func.funcForm || 'B0208Service', {
                            machine_no: 'N/A',
                            plotItem: item,
                            feedback: function () {
                                outSourceInfoGet(function (response) {
                                    $scope.outsourceInfo.outsourcing_info_detail = response;
                                });
                            }
                        });
                    }
                },
                'outsourcing_info_detail.B0209': {
                    isShown: (item, args) => {
                        return ['W'].includes(item.status) ? 'Y' : 'N';
                    },
                    click: (item, args) => {
                        $mdDialog.serviceDialog(args.func.funcForm || 'B0209Service', {
                            machine_no: 'N/A',
                            plotItem: item,
                            feedback: function () {
                                outSourceInfoGet(function (response) {
                                    $scope.outsourceInfo.outsourcing_info_detail = response;
                                });
                            }
                        });
                    }

                },
                'outsourcing_info_detail.B022504': {
                    isShown: (item, args) => {
                        return ['Q'].includes(item.status) ? 'Y' : 'N';
                    },
                    click: (item, args) => {
                        $mdDialog.serviceDialog(args.func.funcForm || 'B0225Service', {
                            machine_no: 'N/A',
                            plotItem: item,
                            callback: function () { }
                        });
                    }

                },
                'outsourcing_info_detail.A0401': {
                    isShown: (item, args) => {
                        return ['Q'].includes(item.status) ? 'Y' : 'N';
                    },
                    click: (item, args) => {
                        $mdDialog.serviceDialog(args.func.funcForm || 'A0401Service', {
                            plotItem: item,
                            feedback: function () {
                                outSourceInfoGet(function (response) {
                                    $scope.outsourceInfo.outsourcing_info_detail = response;
                                });
                            }
                        });
                    }

                },
                'outsourcing_info_detail.A0402': {
                    isShown: (item, args) => {
                        return ['Q'].includes(item.status) ? 'Y' : 'N';
                    },
                    click: (item, args) => {
                        $mdDialog.serviceDialog(args.func.funcForm || 'A0402Service', {
                            plotItem: item,
                            feedback: function () {
                                outSourceInfoGet(function (response) {
                                    $scope.outsourceInfo.outsourcing_info_detail = response;
                                });
                            }
                        });
                    }

                }
            }

            //取得外包明細
            function outSourceInfoGet(feedback) {
                var content = {op_no: $scope.outsourceInfo.op_no, return_type: 0};
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.outsourcing_info_get',
                    content: content,
                    success: function (data) {
                        // 20220313 modify by Alan for M#129264:  取得outsourcing_info_detail時，應清空checkBoxList
                        $scope.checkBoxList = {};
                        //20190109 modify by Dustdusk for M#54174: 作業站的外包商編號預設值不可覆蓋已選的外包商編號
                        if($scope.outsourceInfo.outsourcers_company_no == '' || $scope.outsourceInfo.outsourcers_company_no == undefined)
                            $scope.outsourceInfo.outsourcers_company_no = data.outsourcers_no;

                        data.outsourcing_info_detail.forEach(function (item) {
                            item.qty = item.output_qty;
                            if($scope.checkBoxList[item.plot_no] == undefined)
                                $scope.checkBoxList[item.plot_no] = 99999;//設定為99999

                            // 有開啟紧固件行业包時，如果有預設載具編號，需要在額外取得此載具編號的資訊
                            if($scope.FasteningPackage == 1 || $scope.FasteningPackage == 'Y'){
                                if(item.fastening_info_detail.defaultvehicle){
                                    for(var i = 0; $scope.vehicleList.length; i++){
                                        if(item.fastening_info_detail.defaultvehicle == $scope.vehicleList[i].vehicle_no){
                                            item.fastening_info_detail.vehicle_no = $scope.vehicleList[i].vehicle_no;
                                            item.fastening_info_detail.vehicle_name = $scope.vehicleList[i].vehicle_name;
                                            item.fastening_info_detail.vehicle_weight = $scope.vehicleList[i].vehicle_weight;
                                            item.fastening_info_detail.vehicle_capacity = $scope.vehicleList[i].vehicle_capacity;
                                            break;
                                        } else {
                                            item.fastening_info_detail.vehicle_no = '';
                                            item.fastening_info_detail.vehicle_name = '';
                                            item.fastening_info_detail.vehicle_weight = '';
                                            item.fastening_info_detail.vehicle_capacity = '';
                                        }
                                    }
                                } else {
                                    item.fastening_info_detail.vehicle_no = '';
                                    item.fastening_info_detail.vehicle_name = '';
                                    item.fastening_info_detail.vehicle_weight = '';
                                    item.fastening_info_detail.vehicle_capacity = '';
                                }
                            }            
                        });
                        feedback(data.outsourcing_info_detail);
                    },
                    error:function(data){
                        feedback([]);
                        $rootScope.showAlert(data.Message);
                    }
                });
            }

            $scope.output_qty_click = function (event, item) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialog) {
                        if ((+num) > (+item.qty)) {
                            $scope.$root.showAlert($filter('translate')('B0216.showAlert.column3') + item.qty);
                        } else {
                            item.output_qty = num;
                            item.checked = true;
                            angular.element(target).removeClass('is-focus');
                            dialog.hide();
                        }

                    },
                    function (dialog) {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum: item.output_qty,
                        decimal: true
                    });
            };

            //完成送出
            function outsourcingInfoProcess() {
                //20200623 add by linzh for M#73505：增加防呆，预计开始日期不可晚于预计结束日期
                if ($filter('date')($scope.outsourceInfo.disp_start_time, 'yyyy/MM/dd') > $filter('date')($scope.outsourceInfo.disp_end_time, 'yyyy/MM/dd')) {
                    $scope.$root.showToast($filter('translate')('B0216.showAlert.disp_time_error'), 'error');
                } else {
                    //20170425 增加回寫說明欄位
                    //20200622 modify by linzh for M#73505：增加预计开始时间，预计结束时间
                    var content = {
                        outsourcers_no: $scope.outsourceInfo.outsourcers_no,
                        op_no: $scope.outsourceInfo.op_no,
                        outsourcers_company_no: $scope.outsourceInfo.outsourcers_company_no,
                        description: $scope.outsourceInfo.description,
                        outsourcing_info_detail: [],
                        erp_doc_type: $scope.outsourceInfo.erp_doc_type,
                        ERPDOCType: $scope.warehouseInfo.erp_doc_type,
                        S_Warehouse_No: $scope.warehouseInfo.product_warehouse,
                        S_Storage_Spaces_No: $scope.warehouseInfo.storage,
                        disp_start_time: $filter('date')($scope.outsourceInfo.disp_start_time, 'yyyy/MM/dd'),
                        disp_end_time: $filter('date')($scope.outsourceInfo.disp_end_time, 'yyyy/MM/dd')
                    };

                    var msg = '';
                    if ($scope.outsourceInfo.outsourcing_info_detail.length > 0) {
                        $scope.outsourceInfo.outsourcing_info_detail.forEach(function (item) {
                            // 20200608 modify by WeiTing for M#72310 - 自製+外包可能會同時有 Q狀態 和 W狀態 的生產批，所以卡控只有 Q狀態 的生產批才能送回後台。
                            if ($scope.checkBoxList[item.plot_no] != 99999 && item.status == 'Q') {
                                if(item.output_qty > 0){
                                    content.outsourcing_info_detail.push({
                                        plot_no: item.plot_no,
                                        plot_stamp: item.plot_stamp,
                                        qty: item.output_qty,
                                        fastening_info_detail: item.fastening_info_detail
                                    });
                                } else {
                                    // 批號： item.plot_no 目前數量為 item.output_qty，數量不能小於等於0，請重新輸入
                                    msg = $filter('translate')('B0216.showAlert.column5') + item.plot_no 
                                            + $filter('translate')('B0216.showAlert.column6') + item.output_qty 
                                            + $filter('translate')('B0216.showAlert.column7');                           
                                }
                            }
                        });
                    }

                    if(msg){
                        return $scope.$root.showAlert(msg);
                    } else {
                        fasteningCheck(content.outsourcing_info_detail, function(){
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.outsourcing_info_process',
                                content: content,
                                success: function (data) {
                                    var msg = $filter('translate')('B0216.showAlert.column4') + data.outsourcers_no;
                                    $scope.$root.showToast(msg);
                                    $scope.outsourceInfo.outsourcers_no = moment(new Date()).format('YYYYMMDDHHmmss');
                                    outSourceInfoGet(function (response) {
                                        $scope.warehouseInfo = {};
                                        $scope.outsourceInfo.outsourcing_info_detail = response;
                                        $scope.checkAll = false;
                                        select_count = 0;
                                    });
                                    autoPreview(data.outsourcers_no); // 透過系統參數判斷是否自動預覽外包單
                                }
                            });
                        });
                    }
                }


            }

            $scope.outsource_order = function(item){
                return $scope.checkBoxList[item.plot_no];
            };

            // 透過系統參數判斷是否自動預覽外包單
            function autoPreview(os_no){
                $MMWService.pageNumberInfoGet({
                    form_name: 'PageNo_117',
                    query_condition_info: [
                        {column_name: 'PARAMETERTYPE', query_mode: '0', value: 'SysInfo', merge_condition_model: 'AND' },
                        {column_name: 'PARAMETERNO', query_mode: '0', value: 'PrintShipmentModel', merge_condition_model: 'AND' }
                    ]
                }, function(itemList){
                    if(itemList && itemList.length > 0){
                        if(itemList[0].parameter_value === '1'){
                            var os_detail = [
                                {
                                    os_no: os_no
                                }
                            ];
                            preview(os_detail);
                        }
                    }
                });
            }

            // 預覽外包單
            var pdf_url;
            function preview(os_detail){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.outsource_pdf_get',
                    content : {
                        os_detail : os_detail
                    },
                    success : function(data){

                        for(var i = 0; i < os_detail.length; i++){
                            $scope.printList.push({
                                printNo: os_detail[i].os_no,
                                printType: '4' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                            });
                        }

                        pdf_url = data.outsource_pdf_get[0].url_pdf;
                        if(pdf_url.indexOf('http://') == -1){
                            pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                        }
                        if(config.setting.outsidePDF == 'Y'){
                            var fs = window.nodeRequire('fs'), RuncardPath;
                            try{
                                // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                                RuncardPath = remote.app.getAppPath();
                            }catch(e){
                                RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                            }
                            RuncardPath += '\\www\\Runcard';
                            if(!fs.existsSync(RuncardPath)){
                                fs.mkdirSync(RuncardPath);
                            }

                            // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                            // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                            fs.readdirSync(RuncardPath, (err, files) => {
                                if (err) {
                                    console.log(err);
                                }
                                //listing all files using forEach
                                files.forEach((file) => {
                                    // Do whatever you want to do with the file
                                    fs.unlink(RuncardPath + '/' + file, (err) => {
                                        if (err) {
                                            console.debug(err);
                                        }
                                    })
                                });
                            })
        
                            // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                            let pdfPath = `${ RuncardPath }/RuncardPreview_${ moment().format('YYYYMMDDHHmmss') }.pdf`;
                            $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                                // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                                const { shell } = window.nodeRequire('electron');
                                shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
                            });
                        } else {
                            showPDFViewer(pdf_url);
                        }
                    }
                });
            }

            function showPDFViewer(pdf_url){
                try{
                    window.nodeRequire('nw.gui').Window.open(pdf_url, {
                        title:'PDF Viewer',
                        show: false,
                        icon:'icon/icon.png',
                        focus:true
                    }, function(win) {
                        win.on('loaded', function(){
                            win.show();
                            win.print();
                        });
                    });
                } catch (e){
                    $scope.mode = 'print';
                    document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
                }
            }

            // 列印
            $scope.print = function(){
                if(window.nodeRequire){
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if(sumatraPDF){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })
    
                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            $scope.$root.showLoading();
                            window.nodeRequire('sumatra-pdf').printWithSettings({
                                path: dist_path,
                                success:function(){
                                    printWiplogProcess();
                                    $scope.$root.hideLoading();
                                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                                },
                                error:function(error){
                                    // 20201104 modify by WeiTing for M#77013 - 不清楚為何列印後，實際列印一張紙和輸入成 PDF檔案都會執行 error 區域，所以目前也先列印完成後，把列印詳情回送給後台做記錄。
                                    printWiplogProcess();
                                    $scope.$root.hideLoading();
                                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            };

            // 下載
            $scope.download = function(){
                window.frames['kmi-pdf-panel'].pdf_download();
            };

            // 取消
            $scope.cancel = function(){
                $scope.mode = 'init';
                document.getElementById('kmi-pdf-panel').src = '';
                $scope.printList = [];
            };
            
            // 列印完成後，需把列印詳情回送給後台做記錄
            function printWiplogProcess(){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                    content : {
                        printList: $scope.printList
                    },
                    success : function(){
                        $scope.mode = 'init';
                        $scope.printList = [];
                    }
                });
            }

            // 雙單位計算進站數量
            $scope.calculaterVehicleQty = function(event, VehicleQty, item){ 
                //依照need_vehicle判斷出貨是否需要維護載具資訊
                if(!item.fastening_info_detail.vehicle_name
                    || item.fastening_info_detail.vehicle_name == ''){
                    if(item.fastening_info_detail.need_vehicle == 2){
                        //無維護載具編號，請問是否繼續執行
                        $rootScope.showAlert($filter('translate')('B0206.msg.vehicle_info_empty'));
                        return;
                    }
                }   
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                if(item.fastening_info_detail.molecule > 0 && item.fastening_info_detail.denominator > 0){
                    $calculater.open(function(num,calcDialog){
                        angular.element(target).removeClass('is-focus');
                        if(+num <= 0){
                            // 雙單位數量不能小於等於0
                            $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column6'));
                        } else {
                            var _checkout_qty = calculaterVehicleQtyCallback(+num, item);
                            if(_checkout_qty > 0){
                                if(_checkout_qty > item.qty){
                                    // 轉換數量 + _checkout_qty + 超出可回貨數量 + item.qty +，轉換失敗，請重新輸入
                                    return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column1') + _checkout_qty 
                                        + $filter('translate')('B0216.vehicleMsg.column4') + item.qty
                                        + $filter('translate')('B0216.vehicleMsg.column7'));
                                } else {
                                    item.fastening_info_detail.double_unit_qty = (+num);
                                    item.fastening_info_detail.vehicle_qty = _checkout_qty;
                                    item.output_qty = _checkout_qty;
                                    calcDialog.hide();
                                }
                            } else {
                                // 轉換數量 + _checkout_qty + 小於等於0，轉換失敗，請重新輸入
                                return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column1') + _checkout_qty 
                                    + $filter('translate')('B0216.vehicleMsg.column2') + $filter('translate')('B0216.vehicleMsg.column7'));
                            }
                        }
                    },
                    function(calcDialog){
                        angular.element(target).removeClass('is-focus');
                        calcDialog.hide();
                    },
                    {
                        defaultNum : VehicleQty,
                        decimal : true
                    });
                } else {
                    // 雙單位轉換率分子或分母不得為0
                    $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column3'));
                }
            }

            function calculaterVehicleQtyCallback(num, item){ // 雙單位計算進站數量callback
                var _checkout_qty = CaculateFastening(item.fastening_info_detail, (+num));
                if(item.fastening_info_detail.double_unit_rules == 3){ // 3: 转换数量超出可出货数则取可出货数
                    if(+_checkout_qty > +item.qty){
                        _checkout_qty = +item.qty;
                    }
                } else if(item.fastening_info_detail.double_unit_rules == 4){ // 4: 转换数量小于可出货数取可出货数
                    if(+_checkout_qty < +item.qty){
                        _checkout_qty = +item.qty;
                    }
                } 
                return +_checkout_qty || 0;
            }

            // 更換雙單位轉換率分子
            $scope.changeMoleculeValue = function(event, item){ 
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function(num,calcDialog){
                    angular.element(target).removeClass('is-focus');
                    if(item.fastening_info_detail.double_unit_qty){
                        var originMoleculeValue = item.fastening_info_detail.molecule; // 先保留原本的轉換率分子
                        if(+num == 0){
                            // 已經輸入雙單位數量，不能變更為0
                            return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column5'));
                        } else {
                            item.fastening_info_detail.molecule = (+num); // 先更換轉換率分子進行計算，轉換失敗會在還原
                            var _checkout_qty = calculaterVehicleQtyCallback(+item.fastening_info_detail.double_unit_qty, item);
                            if(_checkout_qty > 0){
                                if(_checkout_qty > item.qty){
                                    item.fastening_info_detail.molecule = originMoleculeValue; // 轉換失敗，需還原原本的轉換率分子
                                    // 轉換數量 + _checkout_qty + 超出可回貨數量 + item.qty +，轉換失敗，請重新輸入
                                    return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column1') + _checkout_qty 
                                        + $filter('translate')('B0216.vehicleMsg.column4') + item.qty
                                        + $filter('translate')('B0216.vehicleMsg.column7'));
                                } else {
                                    item.fastening_info_detail.molecule = (+num);
                                    item.fastening_info_detail.vehicle_qty = _checkout_qty;
                                    item.output_qty = _checkout_qty;
                                    calcDialog.hide();
                                }
                            } else {
                                // 轉換數量 + _checkout_qty + 小於等於0，轉換失敗，請重新輸入
                                return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column1') + _checkout_qty 
                                    + $filter('translate')('B0216.vehicleMsg.column2') + $filter('translate')('B0216.vehicleMsg.column7'));
                            }
                        }
                    } else {
                        item.fastening_info_detail.molecule = (+num);
                        calcDialog.hide();
                    }
                },
                function(calcDialog){
                    angular.element(target).removeClass('is-focus');
                    calcDialog.hide();
                },
                {
                    defaultNum : item.fastening_info_detail.molecule,
                    decimal : true
                });
            }

            // 更換雙單位轉換率分母
            $scope.changeDenominatorValue = function(event, item){ 
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function(num,calcDialog){
                    angular.element(target).removeClass('is-focus');
                    var originDenominatorValue = item.fastening_info_detail.denominator; // 先保留原本的轉換率分母
                    if(item.fastening_info_detail.double_unit_qty){
                        if(+num == 0){
                            // 已經輸入雙單位數量，不能變更為0
                            return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column5'));
                        } else {
                            item.fastening_info_detail.denominator = (+num); // 先更換轉換率分母進行計算，轉換失敗會在還原
                            var _checkout_qty = calculaterVehicleQtyCallback(+item.fastening_info_detail.double_unit_qty, item);
                            if(_checkout_qty > 0){
                                if(_checkout_qty > item.qty){
                                    item.fastening_info_detail.denominator = originDenominatorValue; // 轉換失敗，需還原原本的轉換率分母
                                    // 轉換數量 + _checkout_qty + 超出可回貨數量 + item.qty +，轉換失敗，請重新輸入
                                    return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column1') + _checkout_qty 
                                        + $filter('translate')('B0216.vehicleMsg.column4') + item.qty
                                        + $filter('translate')('B0216.vehicleMsg.column7'));
                                } else {
                                    item.fastening_info_detail.denominator = (+num);
                                    item.fastening_info_detail.vehicle_qty = _checkout_qty;
                                    item.output_qty = _checkout_qty;
                                    calcDialog.hide();
                                }
                            } else {
                                // 轉換數量 + _checkout_qty + 小於等於0，轉換失敗，請重新輸入
                                return $rootScope.showAlert($filter('translate')('B0216.vehicleMsg.column1') + _checkout_qty 
                                    + $filter('translate')('B0216.vehicleMsg.column2') + $filter('translate')('B0216.vehicleMsg.column7'));
                            }
                        } 
                    } else {
                        item.fastening_info_detail.denominator = (+num);
                        calcDialog.hide();
                    }
                },
                function(calcDialog){
                    angular.element(target).removeClass('is-focus');
                    calcDialog.hide();
                },
                {
                    defaultNum : item.fastening_info_detail.denominator,
                    decimal : true
                });
            }
            $scope._event['outsourcing_info_detail.vehicle_no'] = {// 開窗選擇載具編號
                click: (vehicle_no, object) => {
                    var item = $scope.outsourceInfo.outsourcing_info_detail[object.index];
                    $rootScope.showQueryList({
                        header: [
                            { label: $filter('translate')('B0206.trackOut.vehicle_no'), code: 'vehicle_no' },
                            { label: $filter('translate')('B0206.trackOut.vehicle_name'), code: 'vehicle_name' },
                            { label: $filter('translate')('B0206.trackOut.vehicle_weight'), code: 'vehicle_weight' },
                            { label: $filter('translate')('B0206.trackOut.vehicle_capacity'), code: 'vehicle_capacity' }
                        ],
                        query: function (conditions, feedback) {
                            vehicle_no_info_get('', feedback);
                        },
                        selectCode: vehicle_no,
                        confirm: function (selectItem, query_dialog) {
                            item.fastening_info_detail.vehicle_no = selectItem.vehicle_no;
                            item.fastening_info_detail.vehicle_name = selectItem.vehicle_name;
                            item.fastening_info_detail.vehicle_weight = selectItem.vehicle_weight;
                            item.fastening_info_detail.vehicle_capacity = selectItem.vehicle_capacity;
                            item.fastening_info_detail.double_unit_qty = undefined; // 有載具編號的情況，雙單位計算公式會不同，所以刷新載具編號時，也要重新輸入雙單位數量
                            query_dialog.hide();
                        }
                    });
                }
            }


            //雙單位計算進站數量
            function CaculateFastening(fastening_info, qty){
                var _qty = $calculater.decimalMutiple($calculater.decimalSub(qty, fastening_info.vehicle_weight||0), (fastening_info.molecule||1)) / (fastening_info.denominator||1),
                    _accuracy = Math.pow(10, fastening_info.accuracy||0)||1;;
                if(fastening_info.conversion_rules == 0){
                    //無條件進位
                    _qty = Math.ceil(_qty * _accuracy) / _accuracy;
                } else if(fastening_info.conversion_rules == 1){
                    //無條件捨��?
                    _qty = Math.floor(_qty * _accuracy) / _accuracy;
                } else if(fastening_info.conversion_rules == 2){
                    //四捨五入
                    _qty = Math.round(_qty * _accuracy) / _accuracy;
                }
                return _qty;
            }

            //取得載具資訊
            function vehicle_no_info_get(vehicle_no, callback){
                var query_condition_info = [];
                if(vehicle_no && vehicle_no != '')
                    query_condition_info.push({column_name:'VehicleNo', query_mode:'0', value: vehicle_no, merge_condition_model:'AND'});
                $MMWService.pageNumberInfoGet({
                    form_name: 'PageNo_120',
                    query_condition_info:query_condition_info
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            }

            //扣件資訊檢查
            function fasteningCheck(options, callback){
                var msg = '', warring_msg = '';
                //依照need_vehicle判斷進站是否需要維護載具資訊?
                if(config.cache.sys_parameter['FasteningPackage'] == 1){
                    if(options && options.length > 0){
                        for(var i = 0; i < options.length; i++){
                            if(!options[i].fastening_info_detail.vehicle_name
                                || options[i].fastening_info_detail.vehicle_name == ''){
                                if(options[i].fastening_info_detail.need_vehicle == 1){
                                    // 批號： item.plot_no 無維護載具編號，請問是否繼續執行
                                    warring_msg += ($filter('translate')('B0216.showAlert.column5') + options[i].plot_no 
                                        + $filter('translate')('B0206.msg.vehicle_info_warning'));
                                } else if(options[i].fastening_info_detail.need_vehicle == 2){
                                    // 批號： item.plot_no 無維護載具編號，請先維護載具資訊
                                    msg += ($filter('translate')('B0216.showAlert.column5') + options[i].plot_no + 
                                        $filter('translate')('B0206.msg.vehicle_info_empty'));
                                }
                            }
                        }
                    }
                }

                if(msg == ''){
                    if(warring_msg == ''){
                        callback();
                    } else {
                        $rootScope.showConfirm(warring_msg, function(confirm_dialog){
                            confirm_dialog.hide();
                            callback();
                        });
                    }
                } else {
                    $rootScope.showAlert(msg);
                }
            }

        }
    ];
});
